Linkedin Java 檢定題庫 try catch 流程


Posted by c9103205 on 2021-07-02

public static void main(String[] args) {
    try {
        System.out.println("A");
        badMethod();
        System.out.println("B");
    } catch (Exception ex) {
        System.out.println("C");
    } finally {
        System.out.println("D");
    }
}
public static void badMethod() {
    throw new Error();
}
  1. A, B, and D
  2. A, C, and D
  3. C and D
  4. A and D

answer : 4
解析:
本題首先必須明白 Exception 與 Error的差別。
你可點 這裡

走到 badMethod() 這個method後
直接 throw new Error();
注意 Error != Exception
而這裡的catch只會捕捉Exception的情況
故不會印出"C"
最後finally則是不管怎樣都會執行
所以最終答案是 A D
實際程式跑出來的結果如下

A
D
Exception in thread "main" java.lang.Error
    at Main.badMethod(scratch.java:21)
    at Main.main(scratch.java:12)

#linkedin #java







Related Posts

位元運算與邏輯運算與電池燈泡的串聯並聯

位元運算與邏輯運算與電池燈泡的串聯並聯

同步 & 非同步(1) - process & thread

同步 & 非同步(1) - process & thread

Git cherry pick 實戰: 作業分支混到 master commit,但又不想洗掉自己作業的 commit 要怎麼辦?

Git cherry pick 實戰: 作業分支混到 master commit,但又不想洗掉自己作業的 commit 要怎麼辦?


Comments